# # coding: utf8
# import time
# import uuid
#
# import tornado
# from tornado import gen
#
# import cms_config
# from app.base_controller import BaseController
# from app.common import global_space, wzhifuSDK
# from app.models import Goods, GoodsComment, GoodsCategory, GoodsPrice, VideoOrderState, GoodsOrder, AppUser, Feedback
# from libs.util import check_param
# from django.db.models import Q
#
#
# # /api/goods-list
# class GoodList(BaseController):
#     def get(self):
#         category = self.get_argument("category", '')
#
#         if not category:
#             gc = GoodsCategory.objects.filter(state=0).order_by('show_order').first()
#         else:
#             gc = GoodsCategory.objects.filter(state=0).filter(id=category).order_by('show_order').first()
#         vo = Goods.objects.filter(state=0).filter(category=gc). \
#             prefetch_related('price'). \
#             prefetch_related('banner')
#         order = self.get_argument("order", '')
#         if order and 'sales' in order:
#             vo = vo.order_by(order)
#         elif 'price' in order:
#             _list = [key.to_dict(photo_style='/350_320') for key in vo.all()]
#             if order == 'price':
#                 _list.sort(key=lambda k: (k.get('price').get('transaction_price')))
#             if order == '-price':
#                 _list.sort(key=lambda k: (-k.get('price').get('transaction_price')))
#             paginator = self.pagination_list(object_list=_list, page_num=int(self.get_argument("pageNum", 1)))
#             return self.render_json(data=paginator)
#         else:
#             vo = vo.order_by('show_order', '-update_time')
#
#         paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
#
#         paginator['cateory'] = gc.to_dict()
#         return self.render_json(data=paginator)
#
#
# def good_category(time):
#     return [key.to_dict() for key in GoodsCategory.objects.filter(state=0).order_by('show_order').all()]
#
#
# class GoodCategory(BaseController):
#     @gen.coroutine
#     def get(self):
#         self.render_json(data=good_category(1))
#
#
# # /api/goods-top
# class GoodTop(BaseController):
#     def get(self):
#         vo = Goods.objects.filter(state=0). \
#             prefetch_related('price'). \
#             prefetch_related('banner')
#         vo = vo.order_by('show_order', '-update_time')
#         paginator = self.pagination(vo.all(), number_per_page=4, page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
#         return self.render_json(data=paginator)
#
#
# # /api/goods-detail
# class GoodDetail(BaseController):
#     @gen.coroutine
#     def get(self):
#         id = self.get_argument("id", 1)
#
#         vo = Goods.objects.filter(id=id). \
#             prefetch_related('price'). \
#             prefetch_related('banner').first()
#         return self.render_json(data=vo.to_dict(type=2, photo_style='/350_320'))
#
#
# # /goods-comment
# class CommentList(BaseController):
#     def get(self):
#         goods_id = self.get_argument("goods_id")
#         session_id = self.get_argument("session_id", '')
#
#         param = [goods_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         vo = GoodsComment.objects.filter(state=0)
#
#         if session_id:
#             session = global_space.very_session(session_id)
#             if not session:
#                 self.render_json(code=999, msg='session 失效')
#                 return
#             openid = session['openid']
#             us = AppUser.objects.filter(openid=openid).first()
#             vo = vo.filter(user=us)
#
#         good = Goods.objects.filter(id=goods_id).first()
#         if not good:
#             self.render_json(code=1001, msg='参数不正确')
#             return
#         vo = vo.filter(goods=good). \
#             select_related('price').select_related('goods'). \
#             select_related('user').order_by("-create_time")
#         paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
#         return self.render_json(data=paginator)
#
#
# class OrderConfirm(BaseController):
#     def post(self):
#         id = self.get_json_argument("id", '')
#         remark = self.get_json_argument("remark", '')
#         session_id = self.get_json_argument("session_id", '')
#
#         param = [id, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         vo = GoodsOrder.objects.filter(id=id).first()
#         if not vo:
#             self.render_json(code=1001, msg='参数不对')
#             return
#
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         if vo.state.id != 99:
#             self.render_json(code=1004, msg='此状态不允许下单')
#             return
#         openid = session['openid']
#
#         if vo.openid != openid:
#             self.render_json(code=1009, msg='不能修改别人的订单')
#             return
#         state = VideoOrderState.objects.filter(id=1).first()
#         vo.state = state
#         vo.remark = remark
#         vo.save()
#         return self.render_json(data={})
#
#
# class OrderClose(BaseController):
#     def post(self):
#         id = self.get_json_argument("id", '')
#         session_id = self.get_json_argument("session_id", '')
#
#         param = [id, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         vo = GoodsOrder.objects.filter(id=id).first()
#         if not vo:
#             self.render_json(code=1001, msg='参数不对')
#             return
#
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         if vo.state.id != 1:
#             self.render_json(code=1004, msg='此状态不允许下单')
#             return
#         openid = session['openid']
#
#         if vo.openid != openid:
#             self.render_json(code=1009, msg='不能修改别人的订单')
#             return
#         state = VideoOrderState.objects.filter(id=14).first()
#         vo.state = state
#         vo.save()
#         return self.render_json(data={})
#
#
# class OrderCreate(BaseController):
#     def post(self):
#         goods_id = self.get_json_argument("goods_id", '')
#         price_id = self.get_json_argument("price_id", '')
#         num = self.get_json_argument("num", 1)
#         session_id = self.get_json_argument("session_id", '')
#         param = [goods_id, price_id, num, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         openid = session['openid']
#         goods = Goods.objects.filter(id=goods_id).first()
#         price = GoodsPrice.objects.filter(id=price_id).first()
#         if price.inventory <= 0:
#             self.render_json(code=1001, msg='库存不足')
#             return
#
#         fee = price.transaction_price * int(num)
#         if not goods or not price:
#             self.render_json(code=1001, msg='参数错误')
#             return
#
#         if price not in goods.price.all():
#             self.render_json(code=1001, msg='参数错误')
#             return
#
#         state = VideoOrderState.objects.filter(id=99).first()
#
#         data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())
#         order_id = data_str + str(global_space.get_order_id()).zfill(32 - len(data_str))
#
#         data_str = time.strftime('%Y', time.localtime())
#         id = data_str + str(global_space.get_order_id()).zfill(10 - len(data_str))
#
#         vo = GoodsOrder.objects.create(id=id, state=state, goods=goods, good_price=price, price=fee, openid=openid, num=num, order_id=order_id)
#
#         self.render_json(data=vo.get_id())
#
#
# class PayNotify(BaseController):
#     def post(self):
#         # log.info(self.request.body)
#         data = wzhifuSDK.xml_to_dict(self.request.body.decode('utf-8'))
#         openid = data.get('openid')
#         out_trade_no = data.get('out_trade_no')
#         total_fee = data.get('total_fee')
#         transaction_id = data.get('transaction_id')
#         vo = GoodsOrder.objects.filter(openid=openid).filter(order_id=out_trade_no).select_related('state').select_related('goods').select_related('good_price').first()
#         vo.weixin_order_id = transaction_id
#         vo.pay_amount = int(total_fee) / 100
#         # if int(total_fee) / 100==vo.price:
#         state = VideoOrderState.objects.filter(id=15).first()
#         vo.state = state
#         vo.save()
#
#         good_p = GoodsPrice.objects.filter(id=vo.good_price.id).first()
#         good_p.inventory = good_p.inventory + 1
#         good_p.save()
#
#         good = Goods.objects.filter(id=vo.goods.id).first()
#         good.sales = good.sales + 1
#         good.save()
#         self.write('''<xml>
#                     <return_code>SUCCESS</return_code>
#                     <return_msg>OK</return_msg>
#                     </xml>''')
#
#
# class Pay(BaseController):
#     @tornado.web.asynchronous
#     def post(self):
#         session_id = self.get_json_argument("session_id", '')
#         if check_param(session_id):
#             self.render_json(code=1001, msg='参数不全')
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#         openid = session['openid']
#
#         url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
#         http = tornado.httpclient.AsyncHTTPClient()
#
#         id = self.get_json_argument("id", '')
#         remark = self.get_json_argument("remark", '')
#
#         remote_ip = self.request.remote_ip
#         param = [id, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         vo = GoodsOrder.objects.filter(id=id).first()
#
#         if not vo:
#             self.render_json(code=1008, msg='订单不存在')
#             return
#         if vo.state.id != 1:
#             self.render_json(code=1004, msg='此状态不允许付款')
#             return
#
#         if vo.openid != openid:
#             self.render_json(code=1009, msg='不能支付别人的订单')
#             return
#         if remark:
#             vo.remark = remark
#             vo.save()
#
#         data = {"appid": cms_config.app_id,
#                 "openid": vo.openid,
#                 "mch_id": cms_config.mch_id,
#                 "nonce_str": uuid.uuid1().hex,
#                 "body": vo.goods.name,
#                 "sign_type": "MD5",
#                 "out_trade_no": str(vo.order_id),
#                 "total_fee": str(1),
#                 "spbill_create_ip": remote_ip,
#                 "notify_url": "https://api.joyfulmedia.cn/api/goods-order-notify",
#                 "trade_type": "JSAPI"
#                 }
#
#         sign = wzhifuSDK.get_sign(data)
#         data['sign'] = sign
#         http.fetch(url, method='POST', body=wzhifuSDK.trans_dict_to_xml(data),
#                    callback=self.on_response)
#
#     def on_response(self, response):
#         if response.error:
#             self.render_json(code=1002, msg='系统异常')
#         else:
#             sign_data = {}
#             data = wzhifuSDK.xml_to_dict(response.body.decode('utf-8'))
#             if data.get('return_code', '') == 'SUCCESS' and data.get('return_msg', '') == 'OK' and data.get('result_code', '') == 'SUCCESS':
#                 sign_data['nonceStr'] = uuid.uuid1().hex.upper()
#                 sign_data['signType'] = 'MD5'
#                 sign_data['timeStamp'] = str(int(time.time()))
#                 sign_data['appId'] = cms_config.app_id
#                 sign_data['package'] = 'prepay_id=' + data.get('prepay_id', '')
#                 sign_data['sign'] = wzhifuSDK.get_sign(sign_data)
#                 self.render_json(data=sign_data)
#             else:
#                 self.render_json(code=9999, msg='系统错误')
#
#
# class Comments(BaseController):
#     def post(self):
#         id = self.get_json_argument("id", '')
#
#         remark = self.get_json_argument("remark", '')
#         session_id = self.get_json_argument("session_id", '')
#         param = [id, session_id, remark]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         openid = session['openid']
#         vo = GoodsOrder.objects.filter(id=id).first()
#         if not vo:
#             self.render_json(code=1008, msg='订单不存在')
#             return
#         if vo.state.id != 9:
#             self.render_json(code=1004, msg='此状态不允许评论')
#             return
#         if vo.openid != openid:
#             self.render_json(code=1009, msg='不能修改别人的订单')
#             return
#         state = VideoOrderState.objects.filter(id=13).first()
#         vo.state = state
#         vo.save()
#         user = AppUser.objects.filter(openid=vo.openid).first()
#         GoodsComment.objects.create(goods=vo.goods, content=remark, price=vo.good_price, user=user, order_id=vo.id)
#         return self.render_json(data={})
#
#
# class Detail(BaseController):
#     def get(self):
#         id = self.get_argument("id", '')
#         session_id = self.get_argument("session_id", '')
#         param = [id, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         vo = GoodsOrder.objects.filter(id=id).select_related('state').select_related('goods').select_related('good_price').first()
#         openid = session['openid']
#         if vo.openid != openid:
#             self.render_json(code=1009, msg='不能查看别人的订单')
#             return
#         self.render_json(data=vo.to_dict())
#
#
# class List(BaseController):
#     def get(self):
#         session_id = self.get_argument("session_id", '')
#         if check_param(session_id):
#             self.render_json(code=1001, msg='参数不全')
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#         openid = session['openid']
#         state = VideoOrderState.objects.filter(id__in=(99, 14)).all()
#         vo = GoodsOrder.objects.filter(openid=openid).filter(~Q(state__in=state)). \
#             select_related('state').select_related('goods').select_related('good_price').order_by('-create_time')
#         paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
#         return self.render_json(data=paginator)
#
#
# class FeedBack(BaseController):
#     def post(self):
#         content = self.get_json_argument("content", '')
#         session_id = self.get_json_argument("session_id", '')
#
#         param = [content, session_id]
#         if check_param(param):
#             self.render_json(code=1001, msg='参数不全')
#             return
#
#         session = global_space.very_session(session_id)
#         if not session:
#             self.render_json(code=999, msg='session 失效')
#             return
#
#         openid = session['openid']
#         Feedback.objects.create(openid=openid, content=content)
#         return self.render_json(data={})
